(function($){
    //首先备份下jquery的ajax方法
    var _ajax=$.ajax;
    //重写jquery的ajax方法
    $.ajax=function(opt){
        //备份opt中error和success方法
        var fn = {
            error:function(XMLHttpRequest, textStatus, errorThrown){},
            success:function(data, textStatus){}
        }
        if(opt.error){
            fn.error=opt.error;
        }
        if(opt.success){
            fn.success=opt.success;
        }
        //扩展增强处理
        var _opt = $.extend(opt,{
            error:function(XMLHttpRequest, textStatus, errorThrown){
                //错误方法增强处理
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },
            success:function(data, textStatus){
        		var result = "";
            	try{
            		//解密文件
            		result = JSON.parse(CommonUtils.aesDecrypt(data));
            	}catch(e){
            		result = data;
            	}
                //成功回调方法增强处理
                fn.success(result, textStatus);
            }
        });
        return _ajax(_opt);
    };
})(jQuery);

//自定义key
var aes_key = "TMOMP20190422ASE";
//js工具类
var CommonUtils = {
	//获取表单元素值，并封装成集合对象
	getFormJson:function(form) {
		var o = {};
		var a = $(form).serializeArray();
		$.each(a, function () {
			if (o[this.name] !== undefined) {
				if (!o[this.name].push) {
					o[this.name] = [o[this.name]];
				}
				o[this.name].push(this.value == "" ? null : this.value);
			} else {
				o[this.name] = (this.value == "" ? null : this.value);
			}
		});
		return o;
	},
	// 获取当前时间
	getYYMMDD:function(){
		var mydate = new Date();
		return mydate.toLocaleDateString().replace("/", "-");
	},
	//填充Form元素数据
	fillFormData:function($form,jsonStr){
		var obj = eval("("+jsonStr+")");
		var key,value,tagName,type,arr;
		for(x in obj){
			key = x;
			value = obj[x];
			if (!value) {
				value=""
			} 
			$($form+" [name='"+key+"'],[name='"+key+"[]']").each(function(){
				tagName = $(this)[0].tagName;
				type = $(this).attr('type');
				if(tagName=='INPUT'){
					if(type=='radio'){
						$(this).attr('checked',$(this).val()==value);
					}else if(type=='checkbox'){
						if(value instanceof Array){
							arr = value;
						}else{
							arr = value.split(',');
						}
						for(var i =0;i<arr.length;i++){
							if($(this).val()==arr[i]){
								$(this).attr('checked',true);
								break;
							}
						}
					}else{
						$(this).val(value);
					}
				}else if(tagName=='SELECT' || tagName=='TEXTAREA'){
					$(this).val(value);
				} else{
					$(this).html(value);
				}
			});
		}
	},
	//获取当前请求路径参数
	getUrlParam:function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
		var r = window.location.search.substr(1).match(reg); 
		if (r != null) return unescape(r[2]); return null; 
	},
	//获取当前请求路径参数(解析中文乱码的)
	getQueryString:function(name) {   
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");   
      var r = window.location.search.substr(1).match(reg);   
      if (r != null) return decodeURI(r[2]); return null;   
	},
	//设置临时存取放数据
	setTempData:function(key,data) {
		if (window.sessionStorage) {
			localStorage.setItem(key, data);
		}
	},
	//获取临时存储数据
	getTempData:function(key) {
		if (window.sessionStorage) {
			return localStorage.getItem(key);
		}
		return null;
	},
	//判断字符是否为空，返回当前值
	isEmptyReturnStr:function(str){
		if(null != str && "" != str){
			return str;
		}
		return "";
	},
	//判断字符为空，返回boolean类型值
	isEmptyReturnBoolean:function(str){
		if(null != str && "" != str){
			return true;
		}
		return false;
	},
	//判断两个数组的数据是否有公共数据
	existsSameValues:function(a1, a2) {
	    if(a1 instanceof Array && a2 instanceof Array){
	        for (var i=0,iLen=a1.length; i<iLen; i++){
	            for (var j=0,jLen=a2.length; j<jLen; j++){
	                if (a1[i]===a2[j]){
	                    return true;
	                }
	            }
	        }
	    }
	    return false;
	},
	getServerRoot:function(){ //例如：http://localhost:8080/tmomp
		var curWwwPath = window.document.location.href;  
		//获取主机地址之后的目录
		var pathName = window.document.location.pathname;  
		var pos = curWwwPath.indexOf(pathName); //获取主机地址，如： http://localhost:8080  
		var localhostPath = curWwwPath.substring(0, pos); //获取带"/"的项目名，如：/web
		var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);  
		var rootPath = localhostPath + projectName;  
		return rootPath;  
	},
	getServerURL:function(){
		var curWwwPath = window.document.location.href;  
		//获取主机地址之后的目录
		var pathName = window.document.location.pathname;  
		var pos = curWwwPath.indexOf(pathName); //获取主机地址，如： http://localhost:8080 
		var localhostPath = curWwwPath.substring(0, pos);
		return localhostPath;  
	},
	encapsulationData:function(data){//封装uri
		var newData = {};
		var userInfo = CommonUtils.getTempData("userInfo");
		if(userInfo && null != userInfo){
			userInfo = JSON.parse(userInfo);
			if(data && null != data){
				newData = data;
				newData.appId = userInfo.appId;
				newData.secret = userInfo.secret;
			}else{
				newData = {
					appId:userInfo.appId,
					secret:userInfo.secret
				};
			}
		}else{
			newData = data;
		}
		//aes加密
		return CommonUtils.aesEncrypt(JSON.stringify(newData));
	},
	//查询基础数据（下拉框、通过选择器注入）callback 回调
	//tips 提示内容，Str 节点选择器 ，code 基础数据编码，level 基础数据等级，
	findBaseDataOption : function(tips,Str,code,level,callback){
		$(Str).empty();
		var data = {};
		data.baseCode=code;
		data.baseLevel=level;
		$.ajax({url:'/init/baseData/findBaseDataListByCode',
			   data:CommonUtils.encapsulationData(data),
			   type:'post',
			   cache:false,  
			   async: true,
			   dataType:'json',  
			   contentType: "application/json",
			   success:function(data) {  
					if(data!=null){
						var result=data;
						var html="";
						var k=false;
						html=html+'<option value="">请选择'+tips+'</option>';
						for(var i=0;i<result.length;i++){
							if(typeof(baseParentId)=='undefined'||result[i].baseLevel==level){
								html=html+'<option value='+result[i].baseCodeValue+'>'+result[i].baseName+'</option>';
								k=true;
							}
						}
						if(k)$(Str).append(html);
						
					}
					callback && callback();
			    },
			    error : function() { }  
		});
	},
	
	//查询基础数据（下拉框、通过选择器注入）defaultVal 默认
	//tips 提示内容，Str 节点选择器 ，code 基础数据编码，level 基础数据等级，
	findBaseDataOption2 : function(tips,Str,code,level,defaultVal){
		$(Str).empty();
		var data = {};
		data.baseCode=code;
		data.baseLevel=level;
		$.ajax({url:'/init/baseData/findBaseDataListByCode',
			   data:CommonUtils.encapsulationData(data),
			   type:'post',
			   cache:false,  
			   async: true,
			   dataType:'json',  
			   contentType: "application/json",
			   success:function(data) {  
					if(data!=null){
						var result=data;
						var html="";
						var k=false;
						html=html+'<option value="">请选择'+tips+'</option>';
						for(var i=0;i<result.length;i++){
							if(defaultVal!=null&&result[i].baseCodeValue==defaultVal){
								html=html+'<option selected value='+result[i].baseCodeValue+'>'+result[i].baseName+'</option>';
							}else{
								html=html+'<option value='+result[i].baseCodeValue+'>'+result[i].baseName+'</option>';
							}
						}
						$(Str).append(html);
						
					}
			    },
			    error : function() { }  
		});
	},
	//查询基础数据（单选框、通过选择器注入）
	findBaseDataRadio : function(Str,code,level,tagName){
		$(Str).empty();
		var data = {};
		data.baseCode=code;
		data.baseLevel=level;
		$.ajax({url:'/init/baseData/findBaseDataListByCode',
			   data:CommonUtils.encapsulationData(data),
			   type:'post',
			   cache:false,  
			   async: false, //同步 默认为同步 同步得等方法结束才往下走
			   dataType:'json',  
			   contentType: "application/json",
			   success:function(result) {  
					if(result!=null&&result.length>0){
						var html="";
						for(var i=0;i<result.length;i++){
							html=html+'<label class="radio-inline" ><input type="radio" '+(i==0?'checked=""':'')+' name='+tagName+' value='+result[i].baseCodeValue+'>'+result[i].baseName+'</label>';
						}								
						$(Str).append(html);
						//单选复选初始化
						$(Str).iCheck({checkboxClass:"icheckbox_square-blue",radioClass:"iradio_square-blue"});
					}
			    },
			    error : function() { }  
		});
	},
	//查询基础数据（复选框、通过选择器注入）
	findBaseDataCheckbox : function(Str,code,level,tagName){
		$(Str).empty();
		var data = {};
		data.baseCode=code;
		data.baseLevel=level;
		$.ajax({url:'/init/baseData/findBaseDataListByCode',
			   data:CommonUtils.encapsulationData(data),
			   type:'post',
			   cache:false,  
			   async: true,
			   dataType:'json',  
			   contentType: "application/json",
			   success:function(result) {  
					if(result!=null&&result.length>0){
						var html="";
						for(var i=0;i<result.length;i++){
							html=html+'<label class="checkbox-inline" ><input type="checkbox" name='+tagName+' value='+result[i].baseCodeValue+'>'+result[i].baseName+'</label>';
						}								
						$(Str).append(html);
						//单选复选初始化
						$(Str).iCheck({checkboxClass:"icheckbox_square-blue",radioClass:"iradio_square-blue"});
					}
			    },
			    error : function() { }  
		});
	},
	//检查图片是否存在
	checkImgExists:function (imgurl,imgObj) {  
	    var ImgObj = new Image(); //判断图片是否存在 
	    ImgObj.onload=function(){
	        imgObj.attr("src",imgurl);
	    }
	    ImgObj.src = imgurl;
	},
	//获取字符串长度
	getStrLength:function() {  
		var len = 0;  
		for (var i=0; i<this.length; i++) {  
			if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {  
				len += 2;  
			} else {  
				len ++;  
			}  
		}  
		return len;  
	},
	//字符加密
	compile:function(code) {  
	   var c=String.fromCharCode(code.charCodeAt(0)+code.length);  
	   for(var i=1;i<code.length;i++){  
	   c+=String.fromCharCode(code.charCodeAt(i)+code.charCodeAt(i-1));  
	   }  
	   return escape(c);  
	},
	//字符解密
	uncompile:function (code) {  
		if(code!=null){
		   code=unescape(code);  
		   var c=String.fromCharCode(code.charCodeAt(0)-code.length);  
		   for(var i=1;i<code.length;i++){  
			   c+=String.fromCharCode(code.charCodeAt(i)-c.charCodeAt(i-1));  
		   } 
		}
		return c;  
	},
	/**
	 * AES加密
	 */
	aesEncrypt:function(word) {
		//秘钥
		var key = CryptoJS.enc.Utf8.parse(aes_key);
		var srcs = CryptoJS.enc.Utf8.parse(word);
		var encrypted = CryptoJS.AES.encrypt(srcs, key, {
			mode : CryptoJS.mode.ECB,
			padding : CryptoJS.pad.Pkcs7
		});
		return encrypted.toString();
	},
	/**
	 * AES解密
	 */
	aesDecrypt:function(word) {
		//秘钥
		var key = CryptoJS.enc.Utf8.parse(aes_key);
		var decrypt = CryptoJS.AES.decrypt(word, key, {
			mode : CryptoJS.mode.ECB,
			padding : CryptoJS.pad.Pkcs7
		});
		return CryptoJS.enc.Utf8.stringify(decrypt).toString();
	},
	//获取用户微信信息
	getWxUseDetails:function(code) {
		//获取code
		$.ajax({
			url:"/baqsng/rest/wechat/wechatService/getWxUserDetails",
			type:"POST",
			dataType:"json",
			contentType:"application/json",
			data:code,
			success:function(data){
				if(data.result){
					var headImageUrl = data.wxUserInfo.headImageUrl;
		           	var weName =data.wxUserInfo.weName;
		           	$("#divUser img").attr("src",headImageUrl);
		        	$("#divUser span").html(weName);
		        	//设置微信名称与头像
		        	CommonUtils.setTempData("weName",weName);
		        	CommonUtils.setTempData("headImageUrl",headImageUrl);
		         }else{
		       	   //是否重新授权
		       	   //reAuthorize();
		         }
			},
			error:function(data){
				//是否重新授权
				//reAuthorize();
			}
		});	
	}
}

//初始化下拉控件
var initSelect = function(){
	var config = {
		".chosen-select" : {},
		".chosen-select-deselect" : {
			allow_single_deselect : !0
		},
		".chosen-select-no-single" : {
			disable_search_threshold : 10
		},
		".chosen-select-no-results" : {
			no_results_text : "Oops, nothing found!"
		},
		".chosen-select-width" : {
			width : "95%"
		}
	};
	for (var selector in config) {
		$(selector).chosen(config[selector]);
	}
}

//初始化下拉框数据
var initSelectOption = function(obj){
	var formId = (obj.formId) ? obj.formId : "";//当前元素父元素Id
	var docId = obj.docId;//当前元素Id
	var baseCode = obj.baseCode;//获取基础数据code
	var baseLevel = obj.baseLevel;//基础数据层级
	var order = (obj.order) ? obj.order : "last_update_date";
	var async = (obj.async) ? obj.async : true;
	var isClear = (obj.isClear) ? obj.isClear : false;
	var value = (obj.value) ? obj.value : "";
	var extendField1 = (obj.extendField1) ? obj.extendField1:"";
	var extendField2 = (obj.extendField2) ? obj.extendField2:"";
	var extendField3 = (obj.extendField3) ? obj.extendField3:"";
	var extendField4 = (obj.extendField4) ? obj.extendField4:"";
	if(isClear){
		$(formId + " " + docId).empty();
	}
	var param = {
		baseCode:baseCode,
		baseLevel:baseLevel,
		order:order,
		extendField1:extendField1,
		extendField2:extendField2,
		extendField3:extendField3,
		extendField4:extendField4
	}
	$.ajax({
		url:'/init/baseData/findBaseDataListByCode',
		data:CommonUtils.encapsulationData(param),
		async: async,
		type:'post',  
		dataType:'json',  
		contentType: "application/json",
		success:function(result) {  
			if(null != result && result.length > 0){
				var option = "";
				for(var i = 0; i < result.length; i++){
					if(result[i].baseCodeValue == value){
						option +="<option value='"+result[i].baseCodeValue+"' selected='selected'>"+result[i].baseName+"</option>";
					}else{
						option +="<option value='"+result[i].baseCodeValue+"'>"+result[i].baseName+"</option>";
					}
				}
				$(formId + " " + docId).append(option);
			}
	    }
	});
}

//将金额转换成大写
var convertCurrency = function(currencyDigits){
	if(currencyDigits[currencyDigits.length-1]=="."){
		currencyDigits=currencyDigits.substring(0,currencyDigits.length-1)
	}
    var MAXIMUM_NUMBER = 99999999999.99;  //最大值
    // 定义转移字符
    var CN_ZERO = "零";
    var CN_ONE = "壹";
    var CN_TWO = "贰";
    var CN_THREE = "叁";
    var CN_FOUR = "肆";
    var CN_FIVE = "伍";
    var CN_SIX = "陆";
    var CN_SEVEN = "柒";
    var CN_EIGHT = "捌";
    var CN_NINE = "玖";
    var CN_TEN = "拾";
    var CN_HUNDRED = "佰";
    var CN_THOUSAND = "仟";
    var CN_TEN_THOUSAND = "万";
    var CN_HUNDRED_MILLION = "亿";
    var CN_DOLLAR = "圆";
    var CN_TEN_CENT = "角";
    var CN_CENT = "分";
    var CN_INTEGER = "整";
 
    // 初始化验证:
    var integral, decimal, outputCharacters, parts;
    var digits, radices, bigRadices, decimals;
    var zeroCount;
    var i, p, d;
    var quotient, modulus;
 
    // 验证输入字符串是否合法
    if (currencyDigits.toString() == "") {
        //alert("还没有输入数字");
        $("#numVail").html("还没有输入数字")
        $("#Digits").focus();
        return;
    }
 
    //判断是否输入有效的数字格式
    var reg = /^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/;
    if (!reg.test(currencyDigits)) {
        //alert("请输入有效格式数字");
        $("#numVail").html("请输入有效格式数字")
        $("#Digits").focus();
        return;
 
    }
 
    currencyDigits = currencyDigits.replace(/,/g, ""); 
    currencyDigits = currencyDigits.replace(/^0+/, ""); 
    //判断输入的数字是否大于定义的数值
    if (Number(currencyDigits) > MAXIMUM_NUMBER) {
        //alert("您输入的数字太大了");
        $("#numVail").html("您输入的数字太大了")
        $("#Digits").focus();
        return;
    }
    $("#numVail").html("")
    parts = currencyDigits.split(".");
    if (parts.length > 1) {
        integral = parts[0];
        decimal = parts[1];
        decimal = decimal.substr(0, 2);
    }
    else {
        integral = parts[0];
        decimal = "";
    }
    // 实例化字符大写人民币汉字对应的数字
    digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
    radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
    bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
    decimals = new Array(CN_TEN_CENT, CN_CENT);
    
    outputCharacters = "";
    //大于零处理逻辑
    if (Number(integral) > 0) {
        zeroCount = 0;
        for (i = 0; i < integral.length; i++) {
            p = integral.length - i - 1;
            d = integral.substr(i, 1);
            quotient = p / 4;
            modulus = p % 4;
            if (d == "0") {
                zeroCount++;
            }
            else {
                if (zeroCount > 0) {
                    outputCharacters += digits[0];
                }
                zeroCount = 0;
                outputCharacters += digits[Number(d)] + radices[modulus];
            }
            if (modulus == 0 && zeroCount < 4) {
                outputCharacters += bigRadices[quotient];
            }
        }
        outputCharacters += CN_DOLLAR;
    }
    // 包含小数部分处理逻辑
    if (decimal != "") {
        for (i = 0; i < decimal.length; i++) {
            d = decimal.substr(i, 1);
            if (d != "0") {
                outputCharacters += digits[Number(d)] + decimals[i];
            }
        }
    }
    //确认并返回最终的输出字符串
    if (outputCharacters == "") {
        outputCharacters = CN_ZERO + CN_DOLLAR;
    }
    if (decimal == "") {
        outputCharacters += CN_INTEGER;
    }
    //返回人民币大写
    return outputCharacters;
}

/*根据出生日期算出年龄*/
var jsGetAge = function(strBirthday) {
	var returnAge;
	var strBirthdayArr = strBirthday.split("-");
	var birthYear = strBirthdayArr[0];
	var birthMonth = strBirthdayArr[1];
	var birthDay = strBirthdayArr[2];

	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();

	if (nowYear == birthYear) {
		returnAge = 0;//同年 则为0岁
	} else {
		var ageDiff = nowYear - birthYear; //年之差
		if (ageDiff > 0) {
			if (nowMonth == birthMonth) {
				var dayDiff = nowDay - birthDay;//日之差
				if (dayDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			} else {
				var monthDiff = nowMonth - birthMonth;//月之差
				if (monthDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			}
		} else {
			returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
		}
	}
	return returnAge;//返回周岁年龄
}

//错误消息函数处理
var errorFunc =  function(req, status, err) {
	window.setTimeout("",1000);
	var auth = req.getResponseHeader("REQUIRES_AUTH");  
    if(auth == 1){
    	var auth_url = req.getResponseHeader("REQUIRES_AUTH_URL"); 
    	//消息提示款
    	swal({title : "很抱歉",text : "登录超时，请重新登录！",type : "error"},function(){
			//跳转页面
			window.parent.location.href= auth_url;
    	});
    }else{
    	var errMsg = "";
    	if(null != req && req.responseText != null && req.responseText != ""){
    		var fir = req.responseText.indexOf("<body><h1>");
    		var sec = req.responseText.indexOf("</h1>");
    		if(fir > 0 && sec > 0){
    			var errMsg = req.responseText.substring(fir+10,sec);
    			//消息提示款
    	    	swal({title : "很抱歉",text : errMsg, type : "error"},function(){
    				//跳转页面
    				window.parent.location.href= "../error404.html";
    	    	});
    		}
    	}else{
    		//消息提示款
    		swal({title : "很抱歉",text :"系统异常，请联系管理员！" ,type : "error"});
    	}
    }
} 

/**
 ** 加法函数，用来得到精确的加法结果
 ** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
 ** 调用：accAdd(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
var accAdd = function(arg1, arg2) {
    var r1, r2, m, c;
    try {
        r1 = arg1.toString().split(".")[1].length;
    }
    catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    }
    catch (e) {
        r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
        var cm = Math.pow(10, c);
        if (r1 > r2) {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", "")) * cm;
        } else {
            arg1 = Number(arg1.toString().replace(".", "")) * cm;
            arg2 = Number(arg2.toString().replace(".", ""));
        }
    } else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
    }
    return parseFloat((arg1 + arg2) / m);
}



/**
 ** 减法函数，用来得到精确的减法结果
 ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
 ** 调用：accSub(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
var accSub = function(arg1, arg2) {
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split(".")[1].length;
    }
    catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    }
    catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return parseFloat(((arg1 * m - arg2 * m) / m).toFixed(n));
}

//关闭当前选项卡
var closeMenuTab = function(){
	var data_id = $(".J_mainContent", parent.document).find("iframe.J_iframe").not(":hidden").attr("data-id");
	if(data_id == "home.html"){
		return;
	}
	$(".J_menuTabs", parent.document).find(".J_menuTab").filter("[data-id='"+data_id+"']").children("i").click();
}

//bootstrapTable加载成功回调方法
var initLoadSuccess = function(data){
	try{
		if(data && data.result == false){
			//消息提示款
			swal({title : "很抱歉",text :data.msg ,type : "error"});
			return;
		}
		//重置模块，以防"module"中途被替换
		resetModule();
		//设置功能元素权限
		setModule(JSON.parse(CommonUtils.getTempData("module")),"power-a");
		//加载选项卡js文件
		$.getScript("../js/contabs.children.min.js"); 
	}catch(e){
		//消息提示款
		swal({title : "很抱歉",text :"系统异常，请联系管理员！" ,type : "error"});
	}
}

//初始化操作操作弄能模块
var loadModule = function(menuVO){
	//判断是否有操作
	if("#" != menuVO.menuPath && window.location.href.indexOf(menuVO.menuPath) > 0){
		//功能元素集合
		var moduleList = menuVO.moduleList;
		//设置功能元素
		setModule(moduleList,"power-btn");
		//临时存放功能元素
		CommonUtils.setTempData("module",JSON.stringify(moduleList));
	}
}

//重置模块，以防"module"中途被替换
var resetModule = function(){
	var userInfo = CommonUtils.getTempData("userInfo");
	if(userInfo && null != userInfo){
		userInfo=JSON.parse(userInfo);
		var userMenus = userInfo.userMenus;
		//用户菜单
		if(null != userMenus && userMenus.length > 0){
			for(var i = 0; i < userMenus.length ; i++){
				var menu = userMenus[i];
				var clildMenus = menu.childMenus;
				//是否存在下级菜单
				if(existsMenu(clildMenus)){
					for(var j = 0; j < clildMenus.length ; j++){
						//加载功能模块
						loadModule(clildMenus[j]);
					}
				}else{
					//加载功能模块
					loadModule(menu);
				}
			}
		}
	}
}

//设置功能元素
var setModule = function(moduleList,className){
	//当前页面所有功能按钮
	$("body").find("."+className).each(function(){
		var exists = false; 
		if(null != moduleList && moduleList.length > 0){
			//遍历功能块
			for(var i = 0; i < moduleList.length; i++){
				var module = moduleList[i];
				if(moduleList[i].moduleCode == $(this).attr("power")){
					exists = true; 
					break;
				}
			}
		}
		//不存在，删除元素
		if(!exists){
			$(this).remove();
		}
	});
}

//判断子节点中是否含有菜单节点
var existsMenu = function(clildMenus){
	if(null != clildMenus && clildMenus.length > 0){
		for(var i = 0; i < clildMenus.length ; i++){
			if(clildMenus[i].menuType == "0"){
				return true;
			}
		}
	}
	return false;
}

/**
 * 初始化菜单项
 */
var loadMenu = function(data){
	var userMenus = data.userMenus;
	var menuDoc = '<nav class="nav-main">';
	menuDoc += '<ul id="topMain" class="nav nav-pills nav-main">';
	//用户菜单
	if(null != userMenus && userMenus.length > 0){
		for(var i = 0; i < userMenus.length ; i++){
			var menu = userMenus[i];
			var clildMenus = menu.childMenus;
			//是否存在下级菜单
			if(existsMenu(clildMenus)){
				menuDoc += '<li class="dropdown mega-menu">';
				menuDoc += '<a class="dropdown-toggle" id="dropdownMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">';
				if(null != menu.extendField1 && "" != menu.extendField1){
					menuDoc += '<i class="'+menu.extendField1+'"></i>';
				}
				menuDoc += ' '+menu.menuName+' <span class="caret"></span>';
				menuDoc += '</a>';
				menuDoc += '<ul class="dropdown-menu menu" aria-labelledby="dropdownMenu1">';
				//子项
				for(var j = 0; j < clildMenus.length ; j++){
					menuDoc += '<li>';
					if("#" != clildMenus[j].menuPath){
						menuDoc += '<a href="../'+clildMenus[j].menuPath+'">';
					}else{
						menuDoc += '<a href="javascript:void(0)">';
					}
					if(null != menu.extendField1 && "" != menu.extendField1){
						menuDoc += '<i class="'+menu.extendField1+'"></i>';
					}
					menuDoc += ' '+ clildMenus[j].menuName +'</a></li>';
					menuDoc += '</li>';
					//加载功能模块
					loadModule(clildMenus[j]);
				}
				menuDoc += '</ul>';
				menuDoc += '</li>';
			}else{
				menuDoc += '<li class="dropdown">';
				if("#" != menu.menuPath){
					menuDoc += '<a '+ 'class="dropdown-toggle"' +' href="../'+menu.menuPath+'">';
				}else{
					menuDoc += '<a '+ 'class="dropdown-toggle"' +' href="javascript:void(0)">';
				}
				if(null != menu.extendField1 && "" != menu.extendField1){
					menuDoc += '<i class="'+menu.extendField1+'"></i>';
				}
				menuDoc += ' '+ menu.menuName + "</a>";
				menuDoc += "</li>";
				//加载功能模块
				loadModule(menu);
			}
		}
	}
	//用户信息 
	menuDoc += '<li class="dropdown mega-menu">';
	menuDoc += '<a class="dropdown-toggle" id="dropdownMenu1" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><i class="glyphicon glyphicon-user"></i> '+data.name+' <span class="caret"></span>';
	menuDoc += '</a>';
	menuDoc += '<ul class="dropdown-menu menu" aria-labelledby="dropdownMenu1">';
	menuDoc += '<li><a href="../template/person.html"><i class="glyphicon glyphicon-user"></i> 用户信息</a></li>';
	menuDoc += '<li><a href="javascript:quit()"><i class="glyphicon glyphicon-off"></i> 退出登录</a></li>';
	menuDoc += '</ul>';
	menuDoc += '</li>';
	menuDoc += '</ul>';
	menuDoc += '</nav>';
	$("#menus").append(menuDoc);
	//设置单位
	//$(".pc_title").text(CommonUtils.isEmptyReturnStr(data.orgName));
	$(".pc_title").css({"width":"200px","font-size":"20px"});
	if(null != data.orgName && data.orgName != ""){
		//后台登录
		if(data.orgName.length > 8 && data.loginType == 0){
			$(".pc_title").html('<marquee align="left" onMouseOut=this.start() onMouseOver=this.stop() >'+data.orgName+'</marquee>');
		}else{
			$(".pc_title").text(CommonUtils.isEmptyReturnStr(data.orgName));
		}
	}
}

//JS截取字符串多余的为...
var cutstr =  function(str) {
	if(null != str && "" != str){
		var str_length = 0;
		var str_len = 0;
		str_cut = new String();
		str_len = str.length;
		for (var i = 0; i < str_len; i++) {
			a = str.charAt(i);
			str_length++;
			if (escape(a).length > 4) {
				//中文字符的长度经编码之后大于4 
				str_length++;
			}
			str_cut = str_cut.concat(a);
			if (str_length >= 60) {
				str_cut = str_cut.concat("...");
				return str_cut;
			}
		}
		//如果给定字符串小于指定长度，则返回源字符串； 
		if (str_length < 60) {
			return str;
		}
	}else{
		return "";
	}
}

//初始化用户信息
var initUserInfo = function(){
	var userInfo = CommonUtils.getTempData("userInfo");
	if(userInfo && null != userInfo){
		loadMenu(JSON.parse(userInfo));
	}else{
		//获取用户信息
		$.ajax({url:'/init/user/findLoginUser',
			data:JSON.stringify(CommonUtils.encapsulationData({})),
			type:'post',  
			dataType:'json',  
			async:false,//同步请求
			contentType: "application/json",
			success:function(data) {
				if (data && null != data) {
					loadMenu(data);
				}else{
					//跳转页面
					window.location.href="../admin/404.html";
				}
			},
			error : function(req, status, err) {  
				//消息提示款
				errorFunc(req, status, err);
			}  
		});
	}
}
